<template>
  <div>
    <div class="row-header" >
      <div :style="{'display': 'flex','flex-direction': 'row','justify-content': 'flex-start','align-items': 'center','margin-bottom':'10px','overflow-x':$store.state.app.screenWidth<400?'scroll':'auto','width':'100%'}">
        <span style="width: 100px; text-align: right;padding-right:10px;font-size: 12px;color:#777;font-weight: 600;">套餐名称:</span>
        <el-input size="small" v-model="mealNameForSearch" style="width: 200px"></el-input>
      </div>
      <div class="row-form-btn">
        <el-button type="shenda" size="small" icon="el-icon-search" @click="currentPage = 1 ; initData()">
          查询
        </el-button>
      </div>
    </div>
    <div class="split-line"></div>
    <div class="row-main">
      <el-button type="shenda" icon="el-icon-back" size="small" @click="toBack">返回</el-button>
      <el-button type="shenda" icon="el-icon-receiving" size="small" @click="showSetRate">批量操作客户费率</el-button>
      <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }" :data="tableData" tooltip-effect="dark"
                class="row-main-table" @selection-change="handleSelectionChange" v-loading.fullscreen="tableLoading"
                element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.2)">
        <el-table-column prop="id" type="selection" align="center" :fixed="$store.state.app.screenWidth<992?true:false" :width="$store.state.app.screenWidth<992?'80px':'100px'"></el-table-column>
        <el-table-column prop="loginName" label="客户账号" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="mealName" label="套餐名称" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <!--<el-table-column prop="dictMealTypeName" label="套餐类型" align="center"></el-table-column>-->
        <el-table-column prop="officialPrice" label="套餐定价" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="costPrice" label="我方成本" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="salePrice" label="售出价" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="dictTerOfValidityName" label="有效期" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="name" label="操作" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <div>
                <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-button class="operation" @click="toRateSingle(scope.row)">设置费率</el-button>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="row-main-pager"
                     :current-page.sync="currentPage" :page-size="pageSize" layout="total,sizes,prev, pager, next, jumper"
                     :page-sizes="[10,20,50,100]" :total="total" background></el-pagination>
      </div>
      <!--设置费率-->
    </div>
    <el-dialog class="setRateView" title="设置费率" top="33vh" :visible.sync="operation.setRateModel" :append-to-body="true"
               :width="$store.state.app.screenWidth<500?'100%':'500px'">
      <el-form label-width="90px">
        <el-form-item label="返佣比例" label-width="120px">
          <el-input type="text" v-model="rate" size="small">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
      <el-button @click="operation.setRateModel = false" size="small">取 消</el-button>
      <el-button type="primary" size="small" v-preventReClick
                 @click="patchSetRate">确 定</el-button></span>
    </el-dialog>
    <!--单人单套餐设置费率-->
    <el-dialog class="setRateView" title="设置费率" top="33vh" :visible.sync="operation.setRateModelSingle"
               :append-to-body="true" :width="$store.state.app.screenWidth<500?'100%':'500px'">
      <el-form label-width="100px">
        <el-form-item label="下级成本价" >
          <el-input type="text" v-model="rateAmount" style="width: 240px"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
      <el-button @click="operation.setRateModelSingle = false" size="small">取 消</el-button>
      <el-button type="primary" size="small" v-preventReClick @click="singleSetRate">确 定</el-button></span>
    </el-dialog>
  </div>
</template>

<script>
import {listForTeeFeeRate} from '@/api/getData'
import {patchSetRate} from '@/api/getData'

export default {
  name: 'Rate',
  data() {
    return {
      rateAmount: '',
      costPriceSelf: '',
      setMealId: '',
      feeRateId: '',
      rate: "",
      multipleSelection: [],
      checkedIds: [],
      operation: {
        setRateModel: false,
        setRateModelSingle: false,
      },
      mealNameForSearch: "",
      tableData: [],
      total: 0,
      agentName: "",
      agentId: "",
      pageSize: 10,
      currentPage: 1,
      maxPage: 1,
      pagekey: '',
      tableLoading: false,
    }
  },

  created() {
    this.agentName = this.$route.params.agentName;
    this.agentId = this.$route.params.id;
    this.initData()
  },

  methods: {
    async toRateSingle(rate) {
      this.pagekey = await this.$getPageKey();
      this.costPriceSelf = rate.costPrice,
        this.setMealId = rate.id,
        this.feeRateId = rate.feeRateId,
        this.rateAmount = rate.salePrice,
        this.operation.setRateModelSingle = true
    },
    async singleSetRate() {
      this.pagekey = await this.$getPageKey();
      let feeRateList = [];
      const obj = {}
      obj.userId = this.agentId;
      if (this.costPriceSelf > this.rateAmount) {
        this.$message({message: "出库价小于了您的成本价！请重新设置。", type: 'error'})
        this.operation.setRateModel = false;
        return false;
      }
      obj.costPrice = this.rateAmount;
      obj.setMealId = this.setMealId;
      obj.id = this.feeRateId;
      feeRateList.push(obj)
      const returnData = await patchSetRate(feeRateList, {
        pagekey: this.pagekey,
      })
      if (returnData._result) {
        this.$message({message: '操作成功', type: 'success'})
        this.operation.setRateModelSingle = false
        this.initData();
      }
    },
    //获取pageKey
    async getPageKey() {
      this.pagekey = await this.$getPageKey()
    },
    async patchSetRate() {
      let feeRateList = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        const obj = {}
        obj.userId = this.agentId
        let costPriceForUpdate = this.multipleSelection[i].officialPrice * (1 - (this.rate / 100))
        costPriceForUpdate = this.fomatFloat(costPriceForUpdate, 2)
        if (this.multipleSelection[i].costPrice > costPriceForUpdate) {
          this.$message({message: '您设置的第' + (i + 1) + "条数记录，出库价小于了您的成本价！请重新设置。", type: 'error'})
          this.operation.setRateModel = false
          return false;
        }
        obj.costPrice = costPriceForUpdate
        obj.setMealId = this.multipleSelection[i].id
        obj.id = this.multipleSelection[i].feeRateId
        feeRateList.push(obj)
      }

      const returnData = await patchSetRate(feeRateList, {
        pagekey: this.pagekey,
      })
      if (returnData._result) {
        this.$message({message: '操作成功', type: 'success'})
        this.operation.setRateModel = false
        this.initData();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`)
      this.pageSize = val;
      this.currentPage =1;
      this.initData();
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`)
      this.currentPage = val
      this.initData()
    },
    toBack() {
      this.$router.back(-1)
    },
    async showSetRate() {
      if (this.multipleSelection.length !== 0) {
        this.operation.setRateModel = true,
          this.rate = ""
      } else {
        this.$message({message: '请选择要设置费率的套餐', type: 'error'})
      }
      this.pagekey = await this.$getPageKey();

    },
    async initData(theKey) {
      this.tableLoading = true;
      const returnData = await listForTeeFeeRate({
        // userId:this.agentId,
        loginName: this.agentName,
        mealName: this.mealNameForSearch,
        page: {
          current: this.currentPage + '',
          size: this.pageSize + ''
        }
      }, {
        obj: this,
        key: 'tableLoading;' + theKey
      })
      this.tableData = []
      this.total = 0;
      if (returnData._result) {
        // 数据回显
        returnData.data.records.map(item => {
          const obj = {};
          obj.id = item.id;
          obj.feeRateId = item.feeRateId;
          obj.userName = this.agentName;// 代理名称
          obj.loginName = item.loginName; // 代理账号
          obj.mealName = item.mealName; // 套餐名称
          obj.dictFromOperatorName = item.dictFromOperatorName; //所属运营商
          obj.dictMealTypeName = item.dictMealTypeName; // 交易类型
          obj.officialPrice = item.officialPrice; // 套餐定价
          obj.costPrice = item.costPrice; // 我方成本
          obj.salePrice = item.salePrice; // 售出价
          obj.dictTerOfValidityName = item.dictTerOfValidityName; // 有效期
          obj.dictIsTerOfValiditySuperName = item.dictIsTerOfValiditySuperName; //有效期是否叠加
          this.tableData.push(obj)
        })
        this.total = returnData.data.total;
      }
      this.tableLoading = false
    },

    fomatFloat(num, n) {
      var f = parseFloat(num);
      if (isNaN(f)) {
        return false;
      }
      f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); // n 幂
      var s = f.toString();
      var rs = s.indexOf('.');
      //判定如果是整数，增加小数点再补0
      if (rs < 0) {
        rs = s.length;
        s += '.';
      }
      while (s.length <= rs + n) {
        s += '0';
      }
      return s;
    }
  }
}
</script>

<style scoped lang="scss">


.el-popper[x-placement^=bottom] {
  margin-right: -39px;
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}

.el-popper[x-placement^=top] {
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;
  margin-right: -39px;

  button {
    display: block;
  }

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}

.accountView {
  .el-dialog__body {
    .el-form-item /deep/ input {
      border: 0;
      cursor: default;
    }
  }
}

.resetPassword /deep/ .el-dialog__body {
  text-align: center;
  font-size: 14px;
  font-family: 微软雅黑;
  line-height: 40px;
  color: #606266;
  font-weight: 700;
}

.deactivate /deep/ .el-dialog__body {
  text-align: justify;
  font-size: 14px;
  font-family: 微软雅黑;
  line-height: 40px;
  color: #606266;
  font-weight: 700;
}

.cardDetail {
  .el-dialog__body {
    .el-form-item /deep/ input {
      border: 0;
      cursor: default;
    }
  }
}

.cardDetail /deep/ .el-dialog {
  display: flex;
  flex-direction: column;
  height: 80%;

  .el-dialog__body {
    overflow: auto;
  }
}


</style>
